﻿#region Using directives

using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;

using GPSTrackingDBV2.Entities;
using GPSTrackingDBV2.Data;

#endregion

namespace GPSTrackingDBV2.Data.Bases
{	
	///<summary>
	/// This class is the base class for any <see cref="UsersGroupsProviderBase"/> implementation.
	/// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures.
	///</summary>
	public abstract partial class UsersGroupsProviderBaseCore : EntityProviderBase<GPSTrackingDBV2.Entities.UsersGroups, GPSTrackingDBV2.Entities.UsersGroupsKey>
	{		
		#region Get from Many To Many Relationship Functions
		#region GetByUsernameCompanyIdFromUsersByUsersGroups
		
		/// <summary>
		///		Gets UsersGroups objects from the datasource by Username in the
		///		UsersByUsersGroups table. Table UsersGroups is related to table Users
		///		through the (M:N) relationship defined in the UsersByUsersGroups table.
		/// </summary>
		/// <param name="_username"></param>
		/// <param name="_companyId"></param>
		/// <returns>Returns a typed collection of UsersGroups objects.</returns>
		public TList<UsersGroups> GetByUsernameCompanyIdFromUsersByUsersGroups(System.String _username, System.Int32 _companyId)
		{
			int count = -1;
			return GetByUsernameCompanyIdFromUsersByUsersGroups(null,_username, _companyId, 0, int.MaxValue, out count);
			
		}
		
		/// <summary>
		///		Gets GPSTrackingDBV2.Entities.UsersGroups objects from the datasource by Username in the
		///		UsersByUsersGroups table. Table UsersGroups is related to table Users
		///		through the (M:N) relationship defined in the UsersByUsersGroups table.
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_username"></param>
		/// <param name="_companyId"></param>
		/// <remarks></remarks>
		/// <returns>Returns a TList of UsersGroups objects.</returns>
		public TList<UsersGroups> GetByUsernameCompanyIdFromUsersByUsersGroups(System.String _username, System.Int32 _companyId, int start, int pageLength)
		{
			int count = -1;
			return GetByUsernameCompanyIdFromUsersByUsersGroups(null, _username, _companyId, start, pageLength, out count);
		}
		
		/// <summary>
		///		Gets UsersGroups objects from the datasource by Username in the
		///		UsersByUsersGroups table. Table UsersGroups is related to table Users
		///		through the (M:N) relationship defined in the UsersByUsersGroups table.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_username"></param>
		/// <param name="_companyId"></param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of UsersGroups objects.</returns>
		public TList<UsersGroups> GetByUsernameCompanyIdFromUsersByUsersGroups(TransactionManager transactionManager, System.String _username, System.Int32 _companyId)
		{
			int count = -1;
			return GetByUsernameCompanyIdFromUsersByUsersGroups(transactionManager, _username, _companyId, 0, int.MaxValue, out count);
		}
		
		
		/// <summary>
		///		Gets UsersGroups objects from the datasource by Username in the
		///		UsersByUsersGroups table. Table UsersGroups is related to table Users
		///		through the (M:N) relationship defined in the UsersByUsersGroups table.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_username"></param>
		/// <param name="_companyId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		///  <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of UsersGroups objects.</returns>
		public TList<UsersGroups> GetByUsernameCompanyIdFromUsersByUsersGroups(TransactionManager transactionManager, System.String _username, System.Int32 _companyId,int start, int pageLength)
		{
			int count = -1;
			return GetByUsernameCompanyIdFromUsersByUsersGroups(transactionManager, _username, _companyId, start, pageLength, out count);
		}
		
		/// <summary>
		///		Gets UsersGroups objects from the datasource by Username in the
		///		UsersByUsersGroups table. Table UsersGroups is related to table Users
		///		through the (M:N) relationship defined in the UsersByUsersGroups table.
		/// </summary>
		/// <param name="_username"></param>
		/// <param name="_companyId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		///  <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of UsersGroups objects.</returns>
		public TList<UsersGroups> GetByUsernameCompanyIdFromUsersByUsersGroups(System.String _username, System.Int32 _companyId,int start, int pageLength, out int count)
		{
			
			return GetByUsernameCompanyIdFromUsersByUsersGroups(null, _username, _companyId, start, pageLength, out count);
		}


		/// <summary>
		///		Gets UsersGroups objects from the datasource by Username in the
		///		UsersByUsersGroups table. Table UsersGroups is related to table Users
		///		through the (M:N) relationship defined in the UsersByUsersGroups table.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <param name="_username"></param>
		/// <param name="_companyId"></param>
		/// <remarks></remarks>
		/// <returns>Returns a TList of UsersGroups objects.</returns>
		public abstract TList<UsersGroups> GetByUsernameCompanyIdFromUsersByUsersGroups(TransactionManager transactionManager,System.String _username, System.Int32 _companyId, int start, int pageLength, out int count);
		
		#endregion GetByUsernameCompanyIdFromUsersByUsersGroups
		
		#region GetByDepartmentIdFromUsersGroupsByDepartments
		
		/// <summary>
		///		Gets UsersGroups objects from the datasource by DepartmentID in the
		///		UsersGroupsByDepartments table. Table UsersGroups is related to table Departments
		///		through the (M:N) relationship defined in the UsersGroupsByDepartments table.
		/// </summary>
		/// <param name="_departmentId"></param>
		/// <returns>Returns a typed collection of UsersGroups objects.</returns>
		public TList<UsersGroups> GetByDepartmentIdFromUsersGroupsByDepartments(System.Int32 _departmentId)
		{
			int count = -1;
			return GetByDepartmentIdFromUsersGroupsByDepartments(null,_departmentId, 0, int.MaxValue, out count);
			
		}
		
		/// <summary>
		///		Gets GPSTrackingDBV2.Entities.UsersGroups objects from the datasource by DepartmentID in the
		///		UsersGroupsByDepartments table. Table UsersGroups is related to table Departments
		///		through the (M:N) relationship defined in the UsersGroupsByDepartments table.
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_departmentId"></param>
		/// <remarks></remarks>
		/// <returns>Returns a TList of UsersGroups objects.</returns>
		public TList<UsersGroups> GetByDepartmentIdFromUsersGroupsByDepartments(System.Int32 _departmentId, int start, int pageLength)
		{
			int count = -1;
			return GetByDepartmentIdFromUsersGroupsByDepartments(null, _departmentId, start, pageLength, out count);
		}
		
		/// <summary>
		///		Gets UsersGroups objects from the datasource by DepartmentID in the
		///		UsersGroupsByDepartments table. Table UsersGroups is related to table Departments
		///		through the (M:N) relationship defined in the UsersGroupsByDepartments table.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_departmentId"></param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of UsersGroups objects.</returns>
		public TList<UsersGroups> GetByDepartmentIdFromUsersGroupsByDepartments(TransactionManager transactionManager, System.Int32 _departmentId)
		{
			int count = -1;
			return GetByDepartmentIdFromUsersGroupsByDepartments(transactionManager, _departmentId, 0, int.MaxValue, out count);
		}
		
		
		/// <summary>
		///		Gets UsersGroups objects from the datasource by DepartmentID in the
		///		UsersGroupsByDepartments table. Table UsersGroups is related to table Departments
		///		through the (M:N) relationship defined in the UsersGroupsByDepartments table.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_departmentId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		///  <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of UsersGroups objects.</returns>
		public TList<UsersGroups> GetByDepartmentIdFromUsersGroupsByDepartments(TransactionManager transactionManager, System.Int32 _departmentId,int start, int pageLength)
		{
			int count = -1;
			return GetByDepartmentIdFromUsersGroupsByDepartments(transactionManager, _departmentId, start, pageLength, out count);
		}
		
		/// <summary>
		///		Gets UsersGroups objects from the datasource by DepartmentID in the
		///		UsersGroupsByDepartments table. Table UsersGroups is related to table Departments
		///		through the (M:N) relationship defined in the UsersGroupsByDepartments table.
		/// </summary>
		/// <param name="_departmentId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		///  <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of UsersGroups objects.</returns>
		public TList<UsersGroups> GetByDepartmentIdFromUsersGroupsByDepartments(System.Int32 _departmentId,int start, int pageLength, out int count)
		{
			
			return GetByDepartmentIdFromUsersGroupsByDepartments(null, _departmentId, start, pageLength, out count);
		}


		/// <summary>
		///		Gets UsersGroups objects from the datasource by DepartmentID in the
		///		UsersGroupsByDepartments table. Table UsersGroups is related to table Departments
		///		through the (M:N) relationship defined in the UsersGroupsByDepartments table.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <param name="_departmentId"></param>
		/// <remarks></remarks>
		/// <returns>Returns a TList of UsersGroups objects.</returns>
		public abstract TList<UsersGroups> GetByDepartmentIdFromUsersGroupsByDepartments(TransactionManager transactionManager,System.Int32 _departmentId, int start, int pageLength, out int count);
		
		#endregion GetByDepartmentIdFromUsersGroupsByDepartments
		
		#endregion	
		
		#region Delete Methods

		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to delete.</param>
		/// <returns>Returns true if operation suceeded.</returns>
		public override bool Delete(TransactionManager transactionManager, GPSTrackingDBV2.Entities.UsersGroupsKey key)
		{
			return Delete(transactionManager, key.UserGroupId);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="_userGroupId">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public bool Delete(System.Int32 _userGroupId)
		{
			return Delete(null, _userGroupId);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_userGroupId">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public abstract bool Delete(TransactionManager transactionManager, System.Int32 _userGroupId);		
		
		#endregion Delete Methods
		
		#region Get By Foreign Key Functions
		#endregion

		#region Get By Index Functions
		
		/// <summary>
		/// 	Gets a row from the DataSource based on its primary key.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to retrieve.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <returns>Returns an instance of the Entity class.</returns>
		public override GPSTrackingDBV2.Entities.UsersGroups Get(TransactionManager transactionManager, GPSTrackingDBV2.Entities.UsersGroupsKey key, int start, int pageLength)
		{
			return GetByUserGroupId(transactionManager, key.UserGroupId, start, pageLength);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the primary key PK_Groups_1 index.
		/// </summary>
		/// <param name="_userGroupId"></param>
		/// <returns>Returns an instance of the <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> class.</returns>
		public GPSTrackingDBV2.Entities.UsersGroups GetByUserGroupId(System.Int32 _userGroupId)
		{
			int count = -1;
			return GetByUserGroupId(null,_userGroupId, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_Groups_1 index.
		/// </summary>
		/// <param name="_userGroupId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> class.</returns>
		public GPSTrackingDBV2.Entities.UsersGroups GetByUserGroupId(System.Int32 _userGroupId, int start, int pageLength)
		{
			int count = -1;
			return GetByUserGroupId(null, _userGroupId, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_Groups_1 index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_userGroupId"></param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> class.</returns>
		public GPSTrackingDBV2.Entities.UsersGroups GetByUserGroupId(TransactionManager transactionManager, System.Int32 _userGroupId)
		{
			int count = -1;
			return GetByUserGroupId(transactionManager, _userGroupId, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_Groups_1 index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_userGroupId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> class.</returns>
		public GPSTrackingDBV2.Entities.UsersGroups GetByUserGroupId(TransactionManager transactionManager, System.Int32 _userGroupId, int start, int pageLength)
		{
			int count = -1;
			return GetByUserGroupId(transactionManager, _userGroupId, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_Groups_1 index.
		/// </summary>
		/// <param name="_userGroupId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> class.</returns>
		public GPSTrackingDBV2.Entities.UsersGroups GetByUserGroupId(System.Int32 _userGroupId, int start, int pageLength, out int count)
		{
			return GetByUserGroupId(null, _userGroupId, start, pageLength, out count);
		}
		
				
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_Groups_1 index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_userGroupId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns an instance of the <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> class.</returns>
		public abstract GPSTrackingDBV2.Entities.UsersGroups GetByUserGroupId(TransactionManager transactionManager, System.Int32 _userGroupId, int start, int pageLength, out int count);
						
		#endregion "Get By Index Functions"
	
		#region Custom Methods
		
		
		#endregion

		#region Helper Functions	
		
		/// <summary>
		/// Fill a TList&lt;UsersGroups&gt; From a DataReader.
		/// </summary>
		/// <param name="reader">Datareader</param>
		/// <param name="rows">The collection to fill</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">number of rows.</param>
		/// <returns>a <see cref="TList&lt;UsersGroups&gt;"/></returns>
		public static TList<UsersGroups> Fill(IDataReader reader, TList<UsersGroups> rows, int start, int pageLength)
		{
			NetTiersProvider currentProvider = DataRepository.Provider;
            bool useEntityFactory = currentProvider.UseEntityFactory;
            bool enableEntityTracking = currentProvider.EnableEntityTracking;
            LoadPolicy currentLoadPolicy = currentProvider.CurrentLoadPolicy;
			Type entityCreationFactoryType = currentProvider.EntityCreationalFactoryType;
			
			// advance to the starting row
			for (int i = 0; i < start; i++)
			{
				if (!reader.Read())
				return rows; // not enough rows, just return
			}
			for (int i = 0; i < pageLength; i++)
			{
				if (!reader.Read())
					break; // we are done
					
				string key = null;
				
				GPSTrackingDBV2.Entities.UsersGroups c = null;
				if (useEntityFactory)
				{
					key = new System.Text.StringBuilder("UsersGroups")
					.Append("|").Append((System.Int32)reader[((int)UsersGroupsColumn.UserGroupId - 1)]).ToString();
					c = EntityManager.LocateOrCreate<UsersGroups>(
					key.ToString(), // EntityTrackingKey
					"UsersGroups",  //Creational Type
					entityCreationFactoryType,  //Factory used to create entity
					enableEntityTracking); // Track this entity?
				}
				else
				{
					c = new GPSTrackingDBV2.Entities.UsersGroups();
				}
				
				if (!enableEntityTracking ||
					c.EntityState == EntityState.Added ||
					(enableEntityTracking &&
					
						(
							(currentLoadPolicy == LoadPolicy.PreserveChanges && c.EntityState == EntityState.Unchanged) ||
							(currentLoadPolicy == LoadPolicy.DiscardChanges && c.EntityState != EntityState.Unchanged)
						)
					))
				{
					c.SuppressEntityEvents = true;
					c.UserGroupId = (System.Int32)reader[((int)UsersGroupsColumn.UserGroupId - 1)];
					c.OriginalUserGroupId = c.UserGroupId;
					c.Name = (System.String)reader[((int)UsersGroupsColumn.Name - 1)];
					c.EntityTrackingKey = key;
					c.AcceptChanges();
					c.SuppressEntityEvents = false;
				}
				rows.Add(c);
			}
		return rows;
		}		
		/// <summary>
		/// Refreshes the <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> object from the <see cref="IDataReader"/>.
		/// </summary>
		/// <param name="reader">The <see cref="IDataReader"/> to read from.</param>
		/// <param name="entity">The <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> object to refresh.</param>
		public static void RefreshEntity(IDataReader reader, GPSTrackingDBV2.Entities.UsersGroups entity)
		{
			if (!reader.Read()) return;
			
			entity.UserGroupId = (System.Int32)reader[((int)UsersGroupsColumn.UserGroupId - 1)];
			entity.OriginalUserGroupId = (System.Int32)reader["UserGroupID"];
			entity.Name = (System.String)reader[((int)UsersGroupsColumn.Name - 1)];
			entity.AcceptChanges();
		}
		
		/// <summary>
		/// Refreshes the <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> object from the <see cref="DataSet"/>.
		/// </summary>
		/// <param name="dataSet">The <see cref="DataSet"/> to read from.</param>
		/// <param name="entity">The <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> object.</param>
		public static void RefreshEntity(DataSet dataSet, GPSTrackingDBV2.Entities.UsersGroups entity)
		{
			DataRow dataRow = dataSet.Tables[0].Rows[0];
			
			entity.UserGroupId = (System.Int32)dataRow["UserGroupID"];
			entity.OriginalUserGroupId = (System.Int32)dataRow["UserGroupID"];
			entity.Name = (System.String)dataRow["Name"];
			entity.AcceptChanges();
		}
		#endregion 
		
		#region DeepLoad Methods
		/// <summary>
		/// Deep Loads the <see cref="IEntity"/> object with criteria based of the child 
		/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
		/// </summary>
		/// <remarks>
		/// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph.
		/// </remarks>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="entity">The <see cref="GPSTrackingDBV2.Entities.UsersGroups"/> object to load.</param>
		/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
		/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
		/// <param name="childTypes">GPSTrackingDBV2.Entities.UsersGroups Property Collection Type Array To Include or Exclude from Load</param>
		/// <param name="innerList">A collection of child types for easy access.</param>
	    /// <exception cref="ArgumentNullException">entity or childTypes is null.</exception>
	    /// <exception cref="ArgumentException">deepLoadType has invalid value.</exception>
		public override void DeepLoad(TransactionManager transactionManager, GPSTrackingDBV2.Entities.UsersGroups entity, bool deep, DeepLoadType deepLoadType, System.Type[] childTypes, DeepSession innerList)
		{
			if(entity == null)
				return;
			
			//used to hold DeepLoad method delegates and fire after all the local children have been loaded.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
			// Deep load child collections  - Call GetByUserGroupId methods when available
			
			#region UsersByUsersGroupsCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<UsersByUsersGroups>|UsersByUsersGroupsCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'UsersByUsersGroupsCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.UsersByUsersGroupsCollection = DataRepository.UsersByUsersGroupsProvider.GetByUserGroupId(transactionManager, entity.UserGroupId);

				if (deep && entity.UsersByUsersGroupsCollection.Count > 0)
				{
					deepHandles.Add("UsersByUsersGroupsCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<UsersByUsersGroups>) DataRepository.UsersByUsersGroupsProvider.DeepLoad,
						new object[] { transactionManager, entity.UsersByUsersGroupsCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			#region UsersGroupsByDepartmentsCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<UsersGroupsByDepartments>|UsersGroupsByDepartmentsCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'UsersGroupsByDepartmentsCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.UsersGroupsByDepartmentsCollection = DataRepository.UsersGroupsByDepartmentsProvider.GetByUserGroupId(transactionManager, entity.UserGroupId);

				if (deep && entity.UsersGroupsByDepartmentsCollection.Count > 0)
				{
					deepHandles.Add("UsersGroupsByDepartmentsCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<UsersGroupsByDepartments>) DataRepository.UsersGroupsByDepartmentsProvider.DeepLoad,
						new object[] { transactionManager, entity.UsersGroupsByDepartmentsCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			#region DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments
			// RelationshipType.ManyToMany
			if (CanDeepLoad(entity, "List<Departments>|DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments", deepLoadType, innerList))
			{
				entity.DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments = DataRepository.DepartmentsProvider.GetByUserGroupIdFromUsersGroupsByDepartments(transactionManager, entity.UserGroupId);			 
		
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments' loaded. key " + entity.EntityTrackingKey);
				#endif 
				
				if (deep && entity.DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments != null)
				{
					deepHandles.Add("DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments",
						new KeyValuePair<Delegate, object>((DeepLoadHandle< Departments >) DataRepository.DepartmentsProvider.DeepLoad,
						new object[] { transactionManager, entity.DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments, deep, deepLoadType, childTypes, innerList }
					));
				}
			}
			#endregion
			
			
			
			#region UsernameCompanyIdUsersCollection_From_UsersByUsersGroups
			// RelationshipType.ManyToMany
			if (CanDeepLoad(entity, "List<Users>|UsernameCompanyIdUsersCollection_From_UsersByUsersGroups", deepLoadType, innerList))
			{
				entity.UsernameCompanyIdUsersCollection_From_UsersByUsersGroups = DataRepository.UsersProvider.GetByUserGroupIdFromUsersByUsersGroups(transactionManager, entity.UserGroupId);			 
		
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'UsernameCompanyIdUsersCollection_From_UsersByUsersGroups' loaded. key " + entity.EntityTrackingKey);
				#endif 
				
				if (deep && entity.UsernameCompanyIdUsersCollection_From_UsersByUsersGroups != null)
				{
					deepHandles.Add("UsernameCompanyIdUsersCollection_From_UsersByUsersGroups",
						new KeyValuePair<Delegate, object>((DeepLoadHandle< Users >) DataRepository.UsersProvider.DeepLoad,
						new object[] { transactionManager, entity.UsernameCompanyIdUsersCollection_From_UsersByUsersGroups, deep, deepLoadType, childTypes, innerList }
					));
				}
			}
			#endregion
			
			
			
			//Fire all DeepLoad Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			deepHandles = null;
		}
		
		#endregion 
		
		#region DeepSave Methods

		/// <summary>
		/// Deep Save the entire object graph of the GPSTrackingDBV2.Entities.UsersGroups object with criteria based of the child 
		/// Type property array and DeepSaveType.
		/// </summary>
		/// <param name="transactionManager">The transaction manager.</param>
		/// <param name="entity">GPSTrackingDBV2.Entities.UsersGroups instance</param>
		/// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param>
		/// <param name="childTypes">GPSTrackingDBV2.Entities.UsersGroups Property Collection Type Array To Include or Exclude from Save</param>
		/// <param name="innerList">A Hashtable of child types for easy access.</param>
		public override bool DeepSave(TransactionManager transactionManager, GPSTrackingDBV2.Entities.UsersGroups entity, DeepSaveType deepSaveType, System.Type[] childTypes, DeepSession innerList)
		{	
			if (entity == null)
				return false;
							
			#region Composite Parent Properties
			//Save Source Composite Properties, however, don't call deep save on them.  
			//So they only get saved a single level deep.
			#endregion Composite Parent Properties

			// Save Root Entity through Provider
			if (!entity.IsDeleted)
				this.Save(transactionManager, entity);
			
			//used to hold DeepSave method delegates and fire after all the local children have been saved.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();

			#region DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments>
			if (CanDeepSave(entity.DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments, "List<Departments>|DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments", deepSaveType, innerList))
			{
				if (entity.DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments.Count > 0 || entity.DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments.DeletedItems.Count > 0)
				{
					DataRepository.DepartmentsProvider.Save(transactionManager, entity.DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments); 
					deepHandles.Add("DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments",
						new KeyValuePair<Delegate, object>((DeepSaveHandle<Departments>) DataRepository.DepartmentsProvider.DeepSave,
						new object[] { transactionManager, entity.DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments, deepSaveType, childTypes, innerList }
					));
				}
			}
			#endregion 

			#region UsernameCompanyIdUsersCollection_From_UsersByUsersGroups>
			if (CanDeepSave(entity.UsernameCompanyIdUsersCollection_From_UsersByUsersGroups, "List<Users>|UsernameCompanyIdUsersCollection_From_UsersByUsersGroups", deepSaveType, innerList))
			{
				if (entity.UsernameCompanyIdUsersCollection_From_UsersByUsersGroups.Count > 0 || entity.UsernameCompanyIdUsersCollection_From_UsersByUsersGroups.DeletedItems.Count > 0)
				{
					DataRepository.UsersProvider.Save(transactionManager, entity.UsernameCompanyIdUsersCollection_From_UsersByUsersGroups); 
					deepHandles.Add("UsernameCompanyIdUsersCollection_From_UsersByUsersGroups",
						new KeyValuePair<Delegate, object>((DeepSaveHandle<Users>) DataRepository.UsersProvider.DeepSave,
						new object[] { transactionManager, entity.UsernameCompanyIdUsersCollection_From_UsersByUsersGroups, deepSaveType, childTypes, innerList }
					));
				}
			}
			#endregion 
	
			#region List<UsersByUsersGroups>
				if (CanDeepSave(entity.UsersByUsersGroupsCollection, "List<UsersByUsersGroups>|UsersByUsersGroupsCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(UsersByUsersGroups child in entity.UsersByUsersGroupsCollection)
					{
						if(child.UserGroupIdSource != null)
						{
								child.UserGroupId = child.UserGroupIdSource.UserGroupId;
						}

						if(child.UsernameCompanyIdSource != null)
						{
								child.Username = child.UsernameCompanyIdSource.Username;
								child.CompanyId = child.UsernameCompanyIdSource.CompanyId;
						}

					}

					if (entity.UsersByUsersGroupsCollection.Count > 0 || entity.UsersByUsersGroupsCollection.DeletedItems.Count > 0)
					{
						//DataRepository.UsersByUsersGroupsProvider.Save(transactionManager, entity.UsersByUsersGroupsCollection);
						
						deepHandles.Add("UsersByUsersGroupsCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< UsersByUsersGroups >) DataRepository.UsersByUsersGroupsProvider.DeepSave,
							new object[] { transactionManager, entity.UsersByUsersGroupsCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
	
			#region List<UsersGroupsByDepartments>
				if (CanDeepSave(entity.UsersGroupsByDepartmentsCollection, "List<UsersGroupsByDepartments>|UsersGroupsByDepartmentsCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(UsersGroupsByDepartments child in entity.UsersGroupsByDepartmentsCollection)
					{
						if(child.UserGroupIdSource != null)
						{
								child.UserGroupId = child.UserGroupIdSource.UserGroupId;
						}

						if(child.DepartmentIdSource != null)
						{
								child.DepartmentId = child.DepartmentIdSource.DepartmentId;
						}

					}

					if (entity.UsersGroupsByDepartmentsCollection.Count > 0 || entity.UsersGroupsByDepartmentsCollection.DeletedItems.Count > 0)
					{
						//DataRepository.UsersGroupsByDepartmentsProvider.Save(transactionManager, entity.UsersGroupsByDepartmentsCollection);
						
						deepHandles.Add("UsersGroupsByDepartmentsCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< UsersGroupsByDepartments >) DataRepository.UsersGroupsByDepartmentsProvider.DeepSave,
							new object[] { transactionManager, entity.UsersGroupsByDepartmentsCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
			//Fire all DeepSave Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			
			// Save Root Entity through Provider, if not already saved in delete mode
			if (entity.IsDeleted)
				this.Save(transactionManager, entity);
				

			deepHandles = null;
						
			return true;
		}
		#endregion
	} // end class
	
	#region UsersGroupsChildEntityTypes
	
	///<summary>
	/// Enumeration used to expose the different child entity types 
	/// for child properties in <c>GPSTrackingDBV2.Entities.UsersGroups</c>
	///</summary>
	public enum UsersGroupsChildEntityTypes
	{

		///<summary>
		/// Collection of <c>UsersGroups</c> as OneToMany for UsersByUsersGroupsCollection
		///</summary>
		[ChildEntityType(typeof(TList<UsersByUsersGroups>))]
		UsersByUsersGroupsCollection,

		///<summary>
		/// Collection of <c>UsersGroups</c> as OneToMany for UsersGroupsByDepartmentsCollection
		///</summary>
		[ChildEntityType(typeof(TList<UsersGroupsByDepartments>))]
		UsersGroupsByDepartmentsCollection,

		///<summary>
		/// Collection of <c>UsersGroups</c> as ManyToMany for DepartmentsCollection_From_UsersGroupsByDepartments
		///</summary>
		[ChildEntityType(typeof(TList<Departments>))]
		DepartmentIdDepartmentsCollection_From_UsersGroupsByDepartments,

		///<summary>
		/// Collection of <c>UsersGroups</c> as ManyToMany for UsersCollection_From_UsersByUsersGroups
		///</summary>
		[ChildEntityType(typeof(TList<Users>))]
		UsernameCompanyIdUsersCollection_From_UsersByUsersGroups,
	}
	
	#endregion UsersGroupsChildEntityTypes
	
	#region UsersGroupsFilterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlFilterBuilder&lt;UsersGroupsColumn&gt;"/> class
	/// that is used exclusively with a <see cref="UsersGroups"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class UsersGroupsFilterBuilder : SqlFilterBuilder<UsersGroupsColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the UsersGroupsFilterBuilder class.
		/// </summary>
		public UsersGroupsFilterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the UsersGroupsFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public UsersGroupsFilterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the UsersGroupsFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public UsersGroupsFilterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion UsersGroupsFilterBuilder
	
	#region UsersGroupsParameterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="ParameterizedSqlFilterBuilder&lt;UsersGroupsColumn&gt;"/> class
	/// that is used exclusively with a <see cref="UsersGroups"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class UsersGroupsParameterBuilder : ParameterizedSqlFilterBuilder<UsersGroupsColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the UsersGroupsParameterBuilder class.
		/// </summary>
		public UsersGroupsParameterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the UsersGroupsParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public UsersGroupsParameterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the UsersGroupsParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public UsersGroupsParameterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion UsersGroupsParameterBuilder
	
	#region UsersGroupsSortBuilder
    
    /// <summary>
    /// A strongly-typed instance of the <see cref="SqlSortBuilder&lt;UsersGroupsColumn&gt;"/> class
	/// that is used exclusively with a <see cref="UsersGroups"/> object.
    /// </summary>
    [CLSCompliant(true)]
    public class UsersGroupsSortBuilder : SqlSortBuilder<UsersGroupsColumn>
    {
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the UsersGroupsSqlSortBuilder class.
		/// </summary>
		public UsersGroupsSortBuilder() : base() { }

		#endregion Constructors

    }    
    #endregion UsersGroupsSortBuilder
	
} // end namespace
